import datetime

from src.utils.config import logger
from src.utils.db_processor import mysql_prediction_processor
from src.utils.util import get_today, check_date_str, format_date_string


ANOMALY_WINDOW_DAYS = 60
ANOMALY_WINDOW_DAYS_EXCLUDE = 60

def load_anomaly_document_item(start_date=None):
    """

    :param start_date: 起始日期
    :return:
    """
    if start_date is None:
        start_date = get_today() - datetime.timedelta(days=ANOMALY_WINDOW_DAYS)
    else:
        start_date = check_date_str(start_date)

    logger.info('loading anomaly product no start_date@{}'.format(start_date))
    sql = """
    SELECT mapping.document_item_id
    FROM mobile_anomaly_one_day_detection detection 
    JOIN mobile_anomaly_one_day_mapping mapping ON detection.lookup_key =  mapping.lookup_key
    WHERE (detection.audit_status IS NULL OR detection.audit_status = 0) AND detection.create_time >= '{}'
    """.format(format_date_string(start_date))

    return mysql_prediction_processor.load_sql(sql)


def load_anomaly_document_item_exclude(start_date=None,categoryid=1):
    """

    :param start_date: 起始日期
    :return:
    """
    if start_date is None:
        start_date = get_today() - datetime.timedelta(days=ANOMALY_WINDOW_DAYS_EXCLUDE)
    else:
        start_date = check_date_str(start_date) - datetime.timedelta(days=ANOMALY_WINDOW_DAYS_EXCLUDE)

    logger.info('loading anomaly product no start_date@{};category_id@{}'.format(start_date,categoryid))
    sql = """
    select distinct product_no as product_document_no
    from mobile_anomaly_one_day_detection detection
    where create_time>='{}' and  (detection.audit_status IS NULL OR detection.audit_status = 0) and product_Category_id =  {} 
    """.format(format_date_string(start_date),categoryid)

    anomaly_detection= mysql_prediction_processor.load_sql(sql)
    if anomaly_detection.empty:
        return tuple(['no1','no1'])
    # return tuple(anomaly_detection.product_document_no.values)
    # 元组只有一个值时，出现 (1,)
    res= tuple(r[0] for r in anomaly_detection.itertuples(index=False))
    if len(res)==1:
        res=list(res)
        res.append('no1')
        res=tuple(res)
    return res
